(function() {
    "use strict";
    var keywords = [];
    var keyword_data = [];
    var user = JSON.parse(sessionStorage.getItem("user"));
    var keynum = 0;
    var funcAddItem = function(){
      var data = myHttp.getFormJson("#addItem");
      // data.rank_current = parseInt(data.rank_current);
      // data.num_launch   = parseInt(data.num_launch);
      var time_begin = new Date(data.time_begin.replace(/-/g,"/"));
      var time_end = new Date(data.time_end.replace(/-/g,"/"));
      if(time_begin.getTime() > time_end.getTime()){
        mygritter("开始时间不可大于结束时间");
        return;
      }
      keynum++;
      var value = addItem.keyword.value;
      keywords.push(keynum);
      keyword_data.push(data);
      $("#keyword").append('<button class="btn btn-info keyword-item" type="button" data-index="'+keynum+'">'+value+'</button>');
      addItem.reset();
      $('#myModal').modal('hide');
      mygritter('关键字添加成功');
      $("#addItem").validate().resetForm();
    };
    var funcUpdateItem = function(){
      var data = myHttp.getFormJson("#updateItem");
      var time_begin = new Date(data.time_begin.replace(/-/g,"/"));
      var time_end = new Date(data.time_end.replace(/-/g,"/"));
      if(time_begin.getTime() > time_end.getTime()){
        mygritter("开始时间不可大于结束时间");
        return;
      }
      var key = parseInt($("#updateModal").data('index'));
      var index = keywords.indexOf(key);
      var value = updateItem.keyword.value;
      if(index != -1){
        keyword_data[index] = data;
        $('button.keyword-item[data-index="'+key+'"]').html(value);
        updateItem.reset();
        $("#updateItem").validate().resetForm();
        $('#updateModal').modal('hide');
        mygritter('该关键字修改成功');
      }else{
        mygritter('该关键字不存在');
      }
    };
    $(document).on('keyup keydown change',"#otherRemark",function(){
      $("#remark3").val($(this).val());
    });
    $(document).on('click', '.back', function (e) {
  		  window.history.go(-1);
  	});
    $(document).on('click','.keyword-item',function(e){
        updateItem.reset();
        var key = parseInt($(this).data('index'));
        var index = keywords.indexOf(key);
        var data = keyword_data[index];
        console.log(data);
        updateItem.keyword.value = data.keyword;
        updateItem.rank_current.value = data.rank_current;
        updateItem.num_launch.value = data.num_launch;
        updateItem.time_begin.value = data.time_begin;
        updateItem.time_end.value = data.time_end;
        $("#updateModal").data('index',key);
        $("#updateModal").modal('show');
    });
    //$(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii:ss'});
    //$("#test-tags").tagsInput({width: 'atuo'});
    $("#myModal").on('click','.btn-primary',function(e){
        if($("#addItem").validate().form()){
          funcAddItem();
        }
    });
    $("#updateModal").on('click','.btn-primary',function(e){
        if($("#updateItem").validate().form()){
          funcUpdateItem();
        }
    });
    $("#updateModal").on('click','.btn-danger',function(e){
        var key =  parseInt($(this).parents("#updateModal").data('index'));
        var index = keywords.indexOf(key);
        keywords.splice(index,1);
        keyword_data.splice(index,1);
        $('button.keyword-item[data-index="'+key+'"]').remove();
        //updateItem.reset();
        mygritter('该关键字删除成功');
        $("#updateModal").modal('hide');
    });
    var rules = {
          keyword: "required",
          rank_current: "required",
          num_launch: {
              required: true,
              digits:true
          },
          time_begin:"required",
          time_end:"required"};
    var messages = {
        keyword: "请输入关键字",
        rank_current: "请输入关键字排名",
        num_launch: "请输入计划投放量",
        time_begin:"请输入投放开始时间",
        time_end:"请输入投放结束时间"
    };
    $("#addItem").validate({
      rules:rules,
      messages:messages,
      submitHandler:function(form){
        funcAddItem();
      }
    });
    $("#updateItem").validate({
      rules:rules,
      messages:messages,
      submitHandler:function(form){
        funcUpdateItem();
      }
    });


    //填充App应用下拉框
    if($("select#app_id").length > 0){
      $.isLoading({text:"加载应用中"});
      myHttp.getJSON('app',function(data){
          $.isLoading("hide");
          var string="";
          var app = {};//根据AppID记录app所对应的icon
          for(var i=0;i<data.length;i++){
            var item = data[i];
            var id = item.id;
            var name = item.app_store_name;
            app[id] = {
              image:item.image_url,
              app_store_id:item.app_store_id,
              connect_type:item.connect_type,
              app_store_name:name,
              app_store_name_with_source:item.app_store_name_with_source,
              remark:item.remark
            };
            string += '<option value="'+id+'">'+name+'</option>';
          }
          $("select#app_id").append(string);
          var s_app = $("select#app_id").chosen();
          if($("img.app_image").length > 0){
            s_app.change(function(){
              var item = app[$(this).val()];
              $("img.app_image").attr("src",item.image);
              addAdForm.app_store_id.value   =item.app_store_id;
              addAdForm.app_store_name.value =item.app_store_name;
              addAdForm.app_name.value = item.app_store_name_with_source;
              $("#remark").val(item.remark);
            });
          }
      });
    }
    $("#addAdForm").validate({
      submitHandler:function(form){
          if($("select#app_id").val() == ""){
            mygritter("请选择需要投放的应用");
            return;
          }
          if(keyword_data.length == 0){
            mygritter("请至少添加一个关键字投放");
            return;
          }
          var data = myHttp.getFormJson(form);
          // data.app_id = parseInt(data.app_id);
          data.keywords = keyword_data;
          data.company_id = user.id;
          data.company_name = user.company;
          data.mins_try = 3;
          data.price_inner = 120;
          $.isLoading({ text: "Loading" });
          myHttp.postJSON("launch/keyword",data,function(data){
              mygritter("添加成功");
              setTimeout(function(){
                $.isLoading( "hide" );
                window.location.href = "/ad/verify.html#ad-verify";
              },500);
          });
      }
    });

    $(document).on("click",".keyword-add",function(){
      var time = new Date();
      var year = time.getFullYear();
      var month = time.getMonth()+1;
      month = month<10?"0"+month:month;
      var day = time.getDate();
      var hour = time.getHours();
      day = day<10?"0"+day:day;
      hour = hour<10?"0"+hour:hour;
      var minute = time.getMinutes();
      minute = minute < 10?"0"+minute:minute;
      addItem.time_begin.value = year+"-"+month+"-"+day+" "+hour+":"+minute+":00";
      $('#add_end').datetimepicker('setStartDate', addItem.time_begin.value);
    });
    $(document).on('keyup keydown change',"#otherRemark",function(){
      $("#remark2").val($(this).val());
    });
    $(document).on("click",".get-rank",function(){
      var keyword = addItem.keyword.value;
      var id = addAdForm.app_store_id.value;
      myHttp.base(myHttp.asoUrl+"monitor/"+keyword+"/"+id,function(data){
        if(data == -1){
          mygritter("该关键字未录入");
          addItem.rank_current.value = "";
        }else{
          mygritter("获取排名成功");
          addItem.rank_current.value = data;
        }
      });
    });
    var now = myHttp.getDate(new Date());
    $( ".date_form" ).datetimepicker({
      autoclose:true,
      startDate:now,
      format: 'yyyy-mm-dd hh:ii:ss',
    });
    $("input[name='time_begin']").datetimepicker().on('changeDate', function(ev){
      var self = $(this).parents("form").find("input[name='time_end']");
      self.val("");
      self.datetimepicker('setStartDate', ev.delegateTarget.value);
      self.datetimepicker('setEndDate', ev.delegateTarget.value.substr(0,10)+" 23:59:59");
      // $('#add_end').val("");
      // $('#add_end').datetimepicker('setStartDate', ev.delegateTarget.value);
      // $('#add_end').datetimepicker('setEndDate', ev.delegateTarget.value.substr(0,10)+" 23:59:59");
    });
    $("input[name='time_end']").datetimepicker('setEndDate', now+" 23:59:59");
})(jQuery);
